<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

$this->useClass("Action_Community_FeedHandler");
class Action_Node_SaveTopMenu extends Action_Community_FeedHandler {
	public function getFeedModel() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
    $this->rh->UseClass("AggregatedModel_Feed_ReaderItems");
    return new AggregatedModel_Feed_ReaderItems();
	}
  
  function process() {
    if ( !$_REQUEST['items'] || !$_REQUEST['position'] ) {
      print 'error';
      exit;
    }
    
    php_parse_str($_REQUEST['items'], $items);
    
    if ( empty($items) ) {
      print 'error';
      exit;
    }
    
    $position = preg_split( '/,/', $_REQUEST['position'] );
    
    if ( empty($position) ) {
      print 'error';
      exit;
    }
    
    $order = array();
    foreach ( $position as $pos ) {
      if ( preg_match( '/^item(\d+)$/', $pos, $matches ) && !empty($matches[1]) ) {
        $order[] = $matches[1];
      }
    }
    
    $top_menu = array();
    foreach ( $order as $i ) {
      if ( isset($items["item{$i}_text"]) && !empty($items["item{$i}_text"])
      && isset($items["item{$i}_link"]) && !empty($items["item{$i}_link"]) ) {
        $top_menu[] = array(
          'text'=>$items["item{$i}_text"],
          'link'=>$items["item{$i}_link"],
        );
      }
    }
    
    $node = $this->rh->ctx->store->getObject(1);
    $node->data['top_menu'] = $top_menu;
    $node->save();
    
 		$this->rh->UseClass('Action_Node_TopMenu');
		$topMenu = new Action_Node_TopMenu( $this->rh );
		$result = $topMenu->getMenuHtml();
    
    print $result;
    exit;
  }
}
